package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * Author: 笨蛋超人不会飞
 * Date:  10:10
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    UserMapper userMapper;

    @Override
    public User wxLongin(UserLoginDTO userLoginDTO) {
        //使用map携带网址要带的信息
        HashMap<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //先通过调用微信的接口去获取openid
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //解析JSON字符串户获取openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //先判断是否获取成功
        if (openid==null||openid.length()==0){
            //抛出登录失败异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //说明获取了openid，
        //接下来要根据openid去查询数据库，看是否已经存在该用户
        User user = userMapper.findByOpenid(openid);
        //如果查询结果为空，说明该用户不存在，需要创建用户
        if (user==null){
            //创建用户
            //创建用户
            user=new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        return user;


    }
}
